package com.mewp.permission.system.aspect;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mewp.permission.system.annotation.Log;
import com.mewp.permission.system.service.AsyncOperLogService;
import com.mewp.permissions.common.utils.IpUtil;
import com.mewp.permissions.common.utils.JwtHelper;
import com.mewp.permissions.model.po.SysOperLog;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Map;
import java.util.Objects;

/**
 * 操作日志记录处理
 *
 * @author mewp
 * @version 1.0
 * @date 2023/8/6 03:04
 */
@Aspect
@Component
public class LogAspect {
    private static final Logger log = LoggerFactory.getLogger(LogAspect.class);

    @Resource
    private AsyncOperLogService asyncOperLogService;

    /**
     * 切入点。表示在标有@Log注解的方法中进行切入
     */
    @Pointcut("@annotation(com.mewp.permission.system.annotation.Log)")
    public void logPointCut() {
    }

    /**
     * 处理完请求后执行
     *
     * @param joinPoint  切点
     * @param jsonResult 响应结果
     */
    @AfterReturning(pointcut = "logPointCut()", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) {
        handleLog(joinPoint, null, jsonResult);
    }


    private void handleLog(JoinPoint joinPoint, final Exception e, Object jsonResult) {
        try {
            RequestAttributes ra = RequestContextHolder.getRequestAttributes();
            ServletRequestAttributes sra = (ServletRequestAttributes) ra;
            HttpServletRequest request = null;
            if (sra != null) {
                request = sra.getRequest();
            }

            //数据库日志
            SysOperLog operLog = new SysOperLog();
            operLog.setStatus(0);

            //请求地址
            operLog.setOperIp(IpUtil.getIpAddress(request));

            if (request != null) {
                operLog.setOperUrl(request.getRequestURI());
                String token = request.getHeader("token");
                String userName = JwtHelper.getUserName(token);
                operLog.setOperName(userName);
                //设置请求方式
                operLog.setRequestMethod(request.getMethod());
            }

            if (!Objects.isNull(e)) {
                operLog.setStatus(1);
                operLog.setErrorMsg(e.getMessage());
            }

            //设置方法名称
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            operLog.setMethod(className + "." + methodName + "()");

            //处理注解上的参数
            getControllerMethodDescription(joinPoint, operLog, jsonResult);

            //保存数据库
            asyncOperLogService.saveSysLog(operLog);
        } catch (Exception ex) {
            //记录本地异常日志
            log.error("==前置通知异常==");
            log.error("异常信息：" + e.getMessage());
            e.printStackTrace();
        }

    }

    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     *
     * @param joinPoint  切点
     * @param operLog    操作日志
     * @param jsonResult 响应结果
     */
    private void getControllerMethodDescription(JoinPoint joinPoint, SysOperLog operLog,
                                                Object jsonResult) throws Exception {
        Class<?> aClass = joinPoint.getTarget().getClass();
        String name = joinPoint.getSignature().getName();
        Method method = aClass.getMethod(name);
        Log controllerLog = method.getAnnotation(Log.class);

        // 设置action动作
        operLog.setBusinessType(controllerLog.businessType().name());
        // 设置标题
        operLog.setTitle(controllerLog.title());
        // 设置操作人类别
        operLog.setOperatorType(controllerLog.operatorType().name());
        // 是否需要保存request，参数和值
        if (controllerLog.isSaveRequestData()) {
            // 获取参数的信息，传入到数据库中。
            setRequestValue(joinPoint, operLog);
        }
        // 是否需要保存response，参数和值
        if (controllerLog.isSaveResponseData() && Objects.nonNull(jsonResult)) {
            String jsonStr;
            jsonStr = new ObjectMapper().writeValueAsString(jsonResult);
            operLog.setJsonResult(jsonStr);
        }
    }

    /**
     * 获取请求的参数，放到log中
     *
     * @param joinPoint 切点
     * @param operLog   操作日志
     */
    private void setRequestValue(JoinPoint joinPoint, SysOperLog operLog) throws JsonProcessingException {
        String requestMethod = operLog.getRequestMethod();
        if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod)) {
            String params = argsArrayToString(joinPoint.getArgs());
            operLog.setOperParam(params);
        }
    }

    /**
     * 参数拼装
     *
     * @param paramsArray 参数数组
     * @return 参数拼接后的字符串
     */
    private String argsArrayToString(Object[] paramsArray) throws JsonProcessingException {
        StringBuilder params = new StringBuilder();
        if (paramsArray != null) {
            for (Object o : paramsArray) {
                if (!Objects.isNull(o) && !isFilterObject(o)) {
                    String value = new ObjectMapper().writeValueAsString(o);
                    params.append(value).append(" ");
                }
            }
        }
        return params.toString().trim();
    }

    /**
     * 判断是否需要过滤的对象。
     *
     * @param o 对象信息。
     * @return 如果是需要过滤的对象，则返回true；否则返回false。
     */
    public boolean isFilterObject(final Object o) {
        Class<?> clazz = o.getClass();
        if (clazz.isArray()) {
            return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
        } else if (Collection.class.isAssignableFrom(clazz)) {
            Collection collection = (Collection) o;
            for (Object value : collection) {
                return value instanceof MultipartFile;
            }
        } else if (Map.class.isAssignableFrom(clazz)) {
            Map map = (Map) o;
            for (Object value : map.entrySet()) {
                Map.Entry entry = (Map.Entry) value;
                return entry.getValue() instanceof MultipartFile;
            }
        }
        return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse
                || o instanceof BindingResult;
    }
}
